//
//  RoaApi.m
//  MySpaceID.Demo
//
//  Created by Haider Sabri on Thursday10/15/09.
//  Copyright 2009 MySpace. All rights reserved.
//

#import "RoaApi.h"
#import "RoaEndpoints.h"
#import "OAServiceTicket.h"
#import "NSString+URLEncoding.h"

static NSString* kStringBoundary = @"3dfdai2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";

@implementation RoaApi
@synthesize context;
@synthesize responseData;

+ (RoaApi*) apiWithContext:(SecurityContext*) context
{
	RoaApi *api = [[[RoaApi alloc] init]autorelease];
	api.context = [context retain];
	return api;
}

- (void) dealloc{
	
	[context release];
	self.responseData = nil;
	[super dealloc];
}

- (void) clearData{
	// reserved function for future clean up
}

#pragma mark --
#pragma mark API Methods

- (void) addPhoto:(NSInteger)userId albumId:(NSInteger)albumId caption:(NSString*)caption photoData:(NSData*)photoData imageType : (NSString*) imageType{

	[self clearData];
	if(context)
	{
		
		NSString *queryParams = [NSString stringWithFormat:@"xoauth_requestor_id=%d&type=IMAGE&CAPTION=%@", userId, [caption encodedURLParameterString]];
		NSString *urlString = [NSString stringWithFormat:ROA_MEDIA_ITEMS, [NSString stringWithFormat: @"myspace.com.album.%d", albumId], queryParams];
		NSURL *url = [NSURL URLWithString: urlString];
		NSLog(urlString);
		[context makeRequest:url :@"POST" :photoData contentType:imageType :self];
	}
	
}

- (void) addPhoto:(NSInteger)userId albumId:(NSInteger)albumId caption:(NSString*)caption photo:(UIImage*)photo
{

	[self clearData];
	if(context)
	{
		
		NSString *queryParams = [NSString stringWithFormat:@"xoauth_requestor_id=%d&type=IMAGE&CAPTION=%@", userId, [caption encodedURLParameterString]];
		NSString *urlString = [NSString stringWithFormat:ROA_MEDIA_ITEMS, [NSString stringWithFormat: @"myspace.com.album.%d", albumId], queryParams];
		NSURL *url = [NSURL URLWithString: urlString];
		NSLog(urlString);
		
		NSMutableData* body = [NSMutableData data];
		NSString* endLine = [NSString stringWithFormat:@"\r\n--%@\r\n", kStringBoundary];
		
		//[body appendData:[[NSString stringWithFormat:@"--%@\r\n", kStringBoundary]
		//				  dataUsingEncoding:NSUTF8StringEncoding]];
		if (photo) {
			NSData* imageData = UIImageJPEGRepresentation(photo, 0.75);
			
			//[body appendData:[[NSString
			//				   stringWithFormat:@"Content-Disposition: form-data; filename=\"photo\"\r\n"]
			//				  dataUsingEncoding:NSUTF8StringEncoding]];
			//[body appendData:[[NSString
							   //stringWithString:@"Content-Type: image/jpeg\r\n\r\n"]
							  //dataUsingEncoding:NSUTF8StringEncoding]];  
			[body appendData:imageData];
			//[body appendData:[endLine dataUsingEncoding:NSUTF8StringEncoding]];
		}
		
		
		NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15.0];
		
		[request setHTTPMethod:@"POST"];
//		NSString *body = [NSString stringWithFormat:@"userid=%@&password=%@&deviceid=%@", u, p, [[DataManager sharedManager] deviceId]];
//		NSData *bodyData = [body dataUsingEncoding:NSASCIIStringEncoding];
		//[body release];
		[request setHTTPBody:body];
		//[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
		//NSString* contentType = [NSString
			//					 stringWithFormat:@"multipart/form-data; boundary=%@", kStringBoundary];
		NSString* contentType = @"image/jpg";
		[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
		
		
		NSURLResponse* response = nil;
		NSData* responseData;
		@try
		{
			NSLog(@"Sending POST Request");
			responseData     = [NSURLConnection sendSynchronousRequest:request
													 returningResponse:&response
																 error:nil];
		}
		@catch (NSException *exception) {
			NSLog(@"Caught %@%@", [exception name], [exception reason]);
			//SunURLCacheAlertWithError(error);
		}
		NSLog(@"POST Request Returned");
		NSString *dataOutput = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
		NSLog(dataOutput);
		
		[dataOutput release];
		
		
		
		//[context makeRequest:url :@"POST" :body contentType:@"image/jpeg" :self];
	}
}

#pragma mark -
#pragma mark OAResponseDelegate methods

- (void)apiTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data {
	NSString *dataOutput = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	
	NSLog(dataOutput);
	NSLog( [[[ticket response] URL] absoluteString]);
	NSLog( [NSString stringWithFormat:@"%d", [(NSHTTPURLResponse*)[ticket response ] statusCode]]);
	if (ticket.succeeded) {
		self.responseData = data;
	}
	[dataOutput release];
}

-(void) apiTicket:(OAServiceTicket *)ticket didFinishWithError:(NSError *)error {
	NSString *message = [NSString stringWithFormat:@"Error! %@ %@",
						 [error localizedDescription],
						 [error localizedFailureReason]];
	NSLog(message);
}

@end
